import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import router from '@/router'

let instance = axios.create({
  baseURL: "http://localhost:9000/",
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  transformRequest: [function (data, headers) {
    if (headers['Content-Type'] != 'multipart/form-data') {
      return qs.stringify(data, {arrayFormat: 'indices', allowDots: true, skipNulls: true});
    } else {
      return data
    }
  }]
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  let token = sessionStorage.getItem("token");
  //   console.info(config)
  //如果token存在并且不是登录请求 都带上token
  if (token && config.url != 'oauth/oauth/token') {
    //alert(token)
    config.headers['Authorization'] = token
  }
  let user = sessionStorage.getItem("user");
  //如果不是登录请求 且sessionStorage中没有user对象
  if (!user && config.url != 'oauth/oauth/token') {
    //router.push("/");
    //alert(111)
  }
  //console.info(config)
  return config;
}, function (err) {
  return Promise.reject(err);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (err) {
  var config = err.config;
  console.info(err.response);
  if (err.response.status == 401 && err.response.data.error == "unauthorized") {
    router.push("/");
  }
  //如果token过期
  if (err.response.status == 401 && err.response.data.error_description.startsWith("Access token expired")) {
    console.info("access_token过期,获取新token");
    let refresh_token = sessionStorage.getItem("refreshToken");
    /*var p = */instance.post("oauth/oauth/token", {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    }, {
      headers: {'Authorization': 'Basic dXNlci1jbGllbnQ6dXNlci1zZWNyZXQtODg4OA=='}
    }).then(res => {
      console.info("获取新token成功", res);
      let accessToken = res.data.access_token;
      let user = res.data.user;
      sessionStorage.setItem("token", "bearer " + accessToken)
      sessionStorage.setItem("user", JSON.stringify(user))
      sessionStorage.setItem("refreshToken", res.data.refresh_token)
      config.headers['Authorization'] = 'Bearer ' + accessToken
      console.info("带上新token重新发送请求");
      return config;
    }).then(config => {
      return axios(config);
    });
    return p;
  }
  //console.info("access_token不过期，继续执行");
  return Promise.reject(err);


});

Vue.prototype.$http = instance
export default instance
